import api from '../../api/api'
import  url, {
  urlObj
} from '../../api/url'
import { throttle } from '../../utils/util'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    genderOptions:{
      0:'女',
      1:'男'
    },
    userInfo: {},
    username: '',
    phone: '',
    imgUrl:'',
    switchChecked: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserProfile()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getUserProfile()
  },
  getUserProfile() {
    api.get(urlObj.getUserInfo).then(res => {
      if (res.statusCode == '200') {
        let targetUrl = '';
        if(res.data.headImg.indexOf('http') >= 0) {
          targetUrl = res.data.headImg
        } else {
          targetUrl = `${urlObj.imgHost}${res.data.headImg}`
        }
        this.setData({
          userInfo: res.data,
          imgUrl: targetUrl,
          switchChecked:res.data.isOpenMessage === 0 ? false : true
        })
      } else {
        wx.showToast({
          title: res.msg,//提示文字
          duration: 2000,//显示时长
          mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
          icon: 'fail', //图标，支持"success"、"loading"  
        })
      }
    })
  },
  username(e) {
    let { value } = e.detail;
    this.setData({
      username: value
    })
    const params = {
      MemberName: value,
      MemberHeadImg: this.data.userInfo.headImg,
      MemberTel: this.data.userInfo.memberTel,
      Gender: this.data.userInfo.gender
    }
    throttle(this.updateUserInfo(params), 1000)
  },
  phone(e) {
    let { value } = e.detail;
    this.setData({
      phone: value
    })
    const params = {
      MemberName: this.data.userInfo.memberName,
      MemberHeadImg: this.data.userInfo.headImg,
      MemberTel: value,
      Gender: this.data.userInfo.gender
    }
    throttle(this.updateUserInfo(params), 1000)
  },
  handleInputAddress(e) {

  },

  handleLogout(e) {
    api.post(urlObj.logout).then(res => {
      wx.removeStorageSync('token')
      wx.showToast({
        title: res.msg,//提示文字
        duration: 500,//显示时长
        mask: true,//是否显示透明蒙层，防止触摸穿透，默认：false  
        icon: 'none', //图标，支持"success"、"loading"  
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '../login/login',
        })
      }, 500)
    })

  },
  openUsersetting() {
    wx.navigateTo({
      url: '../usersetting/usersetting',
    })
  },
  switchChange(e){
    console.log(e.detail.value)
    let flag = e.detail.value;
    if (flag) {
      this.handleSubscribe()
    } 
    const params = {
      isopen: flag ? 1 : 0
    }
    api.post(urlObj.openMsg,params).then(res => {
      if(res.statusCode === '200') {
        wx.showToast({
          title: flag ? "订阅成功！" : "取消成功",
          duration: 1500,
          icon: "success",
        });
      }
    })
  },
  // 订阅消息
  handleSubscribe() {
    let that = this;
    wx.requestSubscribeMessage({
      tmplIds: ["b6LArh7seonqo1jDeNhxVS4MHLRX8MSbxlJDXsNRdCk"],//需要订阅的消息模板的id的集合，一次调用最多可订阅3条消息
      // 消息模板id在[微信公众平台(mp.weixin.qq.com)-功能-订阅消息]中配置
      success(res) { // 接口调用成功的回调函数
        console.log(res,'compareVersion')
        if (
          res["b6LArh7seonqo1jDeNhxVS4MHLRX8MSbxlJDXsNRdCk"] == "accept"
          // Object res   [TEMPLATE_ID]是动态的键，即模板id，值包括'accept'、'reject'、'ban'。
          // 'accept'表示用户同意订阅该条id对应的模板消息，'reject'表示用户拒绝订阅该条id对应的模板消息，'ban'表示已被后台封禁。
        ) {
          if (that.subscribeMes) {
            wx.showToast({
              title: "订阅成功！",
              duration: 1500,
              icon: "success",
              success(data) {
                that.subscribeMes = false;
              }
            });
            that.getUserProfile()
          }
        } else {
          console.log('err')
        }
      },
      fail(res) { // 接口调用失败的回调函数
        if (res.errCode === 20004) {
          wx.showModal({
            title: "温馨提示",
            content: "您已拒绝授权，将无法在微信中收到回复通知！",
            showCancel: false,
            success: res => {
              if (res.confirm) {
                wx.navigateTo({
                  url: `/pages/map/map`
                });
              }
            }
          });
        }
      }
    });
  },
})

